package com.ellison.zookeeperdemo.id;

import org.I0Itec.zkclient.ZkClient;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * 用 Zookeeper 来当分布式发号器
 * @Classname Id
 * @Description TODO
 * @Author xx
 * Date 2021/6/19 21:41
 * Version 1.0
 */
public class Id {
    private static String connectStr = "119.3.228.104:2181";
    private String root = "/ID";
    private String nodeName = "/order";
    private ZkClient zkClient = null;
    private ExecutorService delExector = null;

    public Id() {
        init();
    }

    private void init() {
        zkClient = new ZkClient(connectStr, 5000);
        delExector = Executors.newFixedThreadPool(10);
        if (!zkClient.exists(root)) {
            zkClient.createPersistent(root);
        }
    }

    private String getId() {
        String nodepath = root.concat(nodeName);
        String ephemeralSequential = zkClient.createEphemeralSequential(nodepath, "");
        System.out.println(ephemeralSequential);

        delExector.execute(() -> zkClient.delete(ephemeralSequential));
        return getId(ephemeralSequential);
    }

    private void stop() {
        delExector.shutdown();
        try {
            delExector.awaitTermination(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(zkClient != null) {
            zkClient.close();
        }
    }

    private String getId(String str) {
        int index = str.lastIndexOf(nodeName);
        return str.substring(index + nodeName.length());
    }

    public static void main(String[] args) {
        Id id = new Id();
        System.out.println(id.getId());
        id.stop();
    }
}
